<template>
    <!-- 表单 -->
    <div>
    <el-form :model="pageParams" label-width="auto" style="margin-top: 20px;margin-left: 30px;">
        <el-row>
            <el-col :span="5">
                <el-form-item label="客户姓名">
                    <el-input v-model="pageParams.name" placeholder="请输入客户姓名" />
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="客户手机" style="margin-left: 35px;">
                    <el-input v-model="pageParams.phone" placeholder="请输入客户手机号码" />
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="归属人" style="margin-left: 35px;">
                    <el-input v-model="pageParams.owner" placeholder="请输入商机归属人" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="7">
                <el-form-item label="跟随时间">
                    <el-date-picker
                    v-model="value1"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item style="margin-left: 35px;">
                    <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                    <el-button :icon="Refresh">重置</el-button>
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 按钮 -->
        <div>
            <el-row style="display: flex;justify-content: space-between;">
                <el-form-item>
                    <el-button type="primary" :icon="Plus" plain>新增</el-button>
                    <el-button type="success" :icon="Edit" plain @click="edit() ">修改</el-button>
                    <el-button type="danger" :icon="Delete" plain @click="del()">删除</el-button>
                    <el-button type="warning" :icon="Download" plain>导出</el-button>
                </el-form-item>
                <el-form-item style="margin-left: 35px; width: 100px;">
                    <el-button :icon="Search" circle />
                <el-button :icon="Refresh" circle />
                </el-form-item>
        </el-row>
        </div>
    </el-form>
    </div>
    <!-- 表格 -->
    <div>
        <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column prop="name" label="客户姓名" width="120">
    </el-table-column>
    <el-table-column prop="phone" label="手机号码" width="120" />
    <el-table-column prop="owner" label="商机归属" />
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column
      prop="status"
      label="商机状态"
      width="100"
    >
      <template #default="scope">
        <!-- <el-tag
          :type="scope.row.status === 'Home' ? 'primary' : 'success'"
          disable-transitions
          >{{ scope.row.tag }}</el-tag
        > -->
        <el-tag v-if="scope.row.status == 1">已分配</el-tag>
        <el-tag type="success" v-if="scope.row.status == 2">跟进中</el-tag>
        <el-tag type="info"  v-if="scope.row.status == 0">未知</el-tag>
        <el-tag type="warning"  v-if="scope.row.status == 4">伪线索</el-tag>
        <el-tag type="danger"  v-if="scope.row.status == 3">回收</el-tag>
      </template>
    </el-table-column>
    <el-table-column property="nextTime" label="下次跟进时间" />
    <el-table-column label="操作">
        <template #default="scope">
            <el-button
            link
            type="primary"
            :icon="View"
            @click="check(scope.row)"
            >
          查看
        </el-button>
            <el-button
            link
            type="primary"
            :icon="Pointer"
            @click.prevent="assign(scope.row)"
            >
            分配
        </el-button>
        <el-button
        link
        type="primary"
        :icon="TopRight"
        @click.prevent="jump(scope.row)"
        >
        跟进
        </el-button>
      </template>
    </el-table-column>
  </el-table>
    </div>
    <!-- 分配对话框 -->
    <el-dialog v-model="dialogVisible" title="分配商机" width="40%">
            <div>
                <el-form ref="assignRuleFormRef" style="width: 700px" :model="assignRuleForm" :rules="rules" label-width="auto">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="归属部门" prop="">
                                <el-tree-select
                                v-model="assignRuleForm.label"
                                :data="treeData"
                                check-strictly
                                :props="treeProps"
                                :render-after-expand="false"
                                style="width: 240px"
                                placeholder="请选择归属部门"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="分配给" prop="">
                                <el-select size="small" v-model="ruleForm.channelId" placeholder="请选择" @change="channelChange">
                                    <el-option v-for="item in assignOptions" :key="item.value" :label="item.nickName"
                                        :value="item.nickName">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(assignRuleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(assignRuleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>

            </div>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
        :title="title"
        v-model="editDialog"
        width="50%">
            <div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="手机号码" prop="phone">
                                <el-input size="small" v-model="ruleForm.phone"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item size="small" label="客户姓名" prop="name">
                                <el-input v-model="ruleForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="渠道来源">
                                <el-select size="small" v-model="ruleForm.channelId" placeholder="请选择" @change="channelChange">
                                <el-option v-for="item in options" :key="item.value" :label="item.channelName"
                                    :value="item.channelId">
                                </el-option>
                            </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item size="small" label="活动信息">
                                <el-select size="small" v-model="ruleForm.activityId" placeholder="请选择">
                                <el-option v-for="item in actOption" :key="item.value" :label="item.name"
                                    :value="item.activityId">
                                </el-option>
                            </el-select>
                    </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="客户性别">
                                <el-radio-group v-model="ruleForm.gender">
                                    <el-radio v-for="(item, index) in sex" :key="index" :label="item.value">{{item.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户年龄">
                                <el-input-number v-model="ruleForm.age" :min="1" :max="100" label="描述文字"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="微信号">
                                <el-input size="small" v-model="ruleForm.weixin"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item size="small" label="QQ号">
                                <el-input v-model="ruleForm.qq"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="EditSubmitForm(ruleFormRef)">确定</el-button>
                <el-button @click="EditResetForm(ruleFormRef)">取消</el-button>
            </span>
    </el-dialog>
    <!-- 分页器 -->
    <page :pageParams="pageParams" :total="total" @size-change="pageChange" @currentChange="handleCurrentChange">
    </page>
</template>
  
<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import page from "@/components/Pagination/page.vue"
import { list, channel, activity, treeselect, detail, delData, updata, followData, assignData, assignment } from "../../../api/list"
import { Search, Refresh, Plus, Edit, Delete, Pointer, Download, TopRight, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TableInstance, FormInstance, FormRules, Action  } from 'element-plus'
import router from '@/router';
import { useRouter } from 'vue-router';

  
// 性别
const sex = [
    {
        label: "男",
        value: 0
    },{
        label: "女",
        value: 1
    },{
        label: "未知",
        value: 2
    },
]
// 搜索按钮
const search = () => {
    pageParams.pageNum = 1
    getList()
}

// 时间日期
const value1 = ref<[Date, Date]>([
//   new Date(2000, 10, 10, 10, 10),
//   new Date(2000, 10, 11, 10, 10),
])

// 编辑按钮
function edit() {
    editDialog.value = true
    title.value = "修改商机"
    // 获取详情
    detail(idList.value).then(res => {
        ruleForm.name = res.data.name
        ruleForm.gender = res.data.gender
        ruleForm.phone = res.data.phone
        ruleForm.qq = res.data.qq
        ruleForm.weixin = res.data.weixin
        ruleForm.age = res.data.age
        if(res.data.channelId) {
           ruleForm.channelId = res.data.channelId
            // 再次调用活动列表
            channelChange(res.data.channelId)
            ruleForm.activityId = res.data.activityId
        }
    })
}
// 分配
let treeData = ref([])
const treeProps = reactive({
    value: 'id',        // 节点值的字段名，这里我们使用id作为值
    label: 'label',     // 节点标签的字段名
    children: 'children' // 子节点的字段名
});
// 分配对话框的确定按钮
function submitForm(){
    // 确定按钮
    assignment().then(res => {
        console.log(res)
    })
    dialogVisible.value = false
}

// 编辑对话框
let title = ref('')
const editDialog = ref(false)

// 编辑对话框的确定按钮
const EditSubmitForm = async (formEl: FormInstance | undefined) => {
    // 将 idList.value 的值赋值给 ruleForm.businessId
    ruleForm.businessId = idList.value;

    updata({
        id: idList.value,
        ...ruleForm
    }).then(res => {
        ElMessage.success("修改成功");
        editDialog.value = false;
        // 重新获取列表数据，将新数据渲染到页面上
        getList();
    })
}



// 取消按钮
const EditResetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    editDialog.value = false
}


// 删除按钮
function del() {
ElMessageBox.confirm(
    `此操作将永久删除编号为${idList.value}的数据, 是否继续?`,
    '系统提示',
    {
      distinguishCancelAndClose: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  )
    .then(() => {
        delData(idList.value).then(res => {
           getList()
            ElMessage({
                type: 'warning',
                message: '删除成功',
            })
        })
    })
}


// 表格
interface User {
  id: number
  date: string
  name: string
  address: string
  tag: string,
  businessId: string
}

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])

const idList = ref()
const selectable = (row: User) => ![1, 2].includes(row.id)
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(val)
    const info = JSON.parse(JSON.stringify(val))
    console.log(info)
    idList.value = val[0].businessId
    console.log(idList.value)
}

// 表格数据
const tableData: any = ref([])

// 查看按钮
function check(row: any){
    console.log('当前行数据:', row);
    router.push({ 
        path: `/business/details/index/${row.id}/view`,
        query: { ...row }
    });
}

// 分配按钮
function assign() {
    dialogVisible.value = true
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
    // 树形选择器
    treeselect().then(res => {
        console.log(res)
        treeData.value = res.data
    })
}
// 跟进按钮
// function jump() {
//     console.log('当前行线索ID:', idList.value);
//     router.push({ path: `/business/follow/index/${idList.value}/follow` });
//     followData().then(res => {
//         ruleForm.name = res.data.name
//         ruleForm.phone = res.data.phone
//         ruleForm.weixin = res.data.weixin
//         ruleForm.age = res.data.age
//         ruleForm.qq = res.data.qq
//         ruleForm.gender = res.data.gender
//         ruleForm.status = res.data.status
//         ruleForm.nextTime = res.data.nextTime
//     })
// }


// function jump(businessId: any) {
//     console.log('当前行线索ID:', businessId);
//     router.push({ 
//         path: `/business/follow/index/${businessId}/follow`,
//         query: { businessId }
//     });
// }
// 跟进按钮
function jump(row: any) {
    console.log('当前行线索ID:', row.businessId);
    router.push({ 
        path: `/business/follow/index/${row.businessId}/follow`,
        query: { 
            businessId: row.businessId,
            createBy: row.owner,
            createTime: row.createTime
        }
    });
}

// 分配对话框
const dialogVisible = ref(false)
interface AssignRuleForm {
    label:string,
    region: string
}
const assignRuleFormRef = ref < FormInstance > ()
const assignRuleForm = reactive < AssignRuleForm > ({
    label:'',
    region: ''
})


// 修改对话框的数据
interface RuleForm {
    name: string,
    gender: number,
    phone: string,
    qq: string,
    weixin: string,
    age: number,
    activityId: number,
    businessId: null,
    channelId: null,
    createTime: string,
    nextTime: string,
    owner: string,
    status: number
}
const ruleFormRef = ref < FormInstance > ()
const ruleForm = reactive < RuleForm > ({
    name: '',
    gender: 1,
    phone: '',
    qq: '',
    weixin: '',
    age: 0,
    activityId: 1,
    businessId: null,
    channelId: null,
    createTime: '',
    nextTime: '',
    owner: '',
    status: 1
})
const rules = reactive <FormRules<RuleForm>>({
    region: [
        {
            required: true,
            message: '部门ID不能为空',
            trigger: 'change',
        },
    ]
})
// 树形选择器
const label = ref()
const data = [
    {   
        label: '',
        children: [{}]
    }
    // {
    //     value: '1',
    //     label: 'Level one 1',
    //     children: [
    //         {
    //             value: '1-1',
    //             label: 'Level two 1-1',
    //             children: [
    //                 {
    //                     value: '1-1-1',
    //                     label: 'Level three 1-1-1',
    //                 },
    //             ],
    //         },
    //     ],
    // }
]
// 分配对话框的取消按钮
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogVisible.value = false
}

// 分页器
let total = ref(0)
    // id
let id = ref(0)
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    phone: '',
    owner: '',

})
onMounted(() => {
    getList()
})

// 分页器
// 接收子传父数据 条数改变时
const pageChange = (val: number) => {
    pageParams.pageNum = 1
    pageParams.pageSize = val
    getList()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    pageParams.pageNum = val
    getList()
}

 // 渠道来源发生变化时触发
function channelChange(val){
    // 每次获取完渠道来源的时候，把活动信息的数据清空，每个渠道来源对应的活动信息数据都是不同的
    ruleForm.activityId = null
    // 渠道来源发生变化的时候，渲染出活动信息的数据
    activity(val).then(res => {
        actOption.value = res.data
    })
}

// 列表
const options = ref()
const actOption = ref()
const assignOptions = ref()
function getList() {
    list(pageParams).then(res => {
        console.log(res)
        tableData.value = res.rows
        total.value = res.total
    })
    channel().then(res => {
        options.value = res.data
    })
    assignData().then(res => {
        assignOptions.value = res.data
    })
}

</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 100px;
}

:deep(.el-form-item__label){
    font-size: 16px;
    font-weight: 600;
}
</style>
  